package net.biancheng.exception;

import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author: lb
 * @Date: 2021/8/18 14:27
 * <p>
 * <p>
 * 自定义异常处理类
 * <p>
 * 被 @ControllerAdvice 注解的类可以用来实现全局异常处理
 */
@ControllerAdvice
public class MyExceptionHandler {

    @ExceptionHandler(CustomException.class)
    public String handleException(Exception e, HttpServletRequest request) {
        Map<String, Object> map = new HashMap<>();
        //向request 对象传入错误状态码
        request.setAttribute("javax.servlet.error.status_code", 500);
        //根据当前处理的异常，自定义返回错误数据
        map.put("code", 500);
        map.put("message", e.getMessage());
        //将自定义的错误数据传入request中
        request.setAttribute("ext", map);
        return "forward:/error";
    }
}
